define(function (require, exports, module) {
    'use strict';
    
    var rk = require('rk');

    $.widget('rk.todayWorkCtrl', {
        _create: function () {
            var me = this;
            var elem = me.element;
            me._listeners();

            me._bindHandler();
        },
        _listeners:function(){
            var me = this,
                elem = this.element;
        },
        _init: function(){
            var me = this;
            var elem = me.element;

            me._loadData();
        },
        _loadData: function(){
            var me = this;
            var elem = me.element;

            rk.post("/json/crm_schedule/index-today-list.action", {}, function(json) {
                if (json.status == 0) {
                    me.data = json.data;
                    me.data.defaultNumber = 5;
                    me.data.total = me.data.schedules.length + me.data.tasks.length;
                    //me.data.scheduleNumber = me.data.schedules.length;

                    me._formatData(me.data);

                    var html = rk.templateText(require('../../../tmpl/index/todaywork/tpl_index_today_work.tpl'), {
                        data: me.data
                    });
                    elem.html(html);

                    me._initPage(me.data);

                    if(me.data.total > me.data.defaultNumber){
                        for(var i=me.data.defaultNumber; i<=me.data.total; i++){
                            elem.find("li[act=task_" + i + "]").eq(0).hide();
                        }
                        //填写更多条
                        elem.find("span[act=morenumber]:eq(0)").text(me.data.total-me.data.defaultNumber);
                    } else {
                        //隐藏更多
                        elem.find("a[act=more]").eq(0).hide();
                    }

                    //设置过期条数
                    elem.find("span[act=taskduenumber]:eq(0)").text(me.data.overDueCount);
                    elem.find("span[act=taskduenumber]:eq(1)").text(me.data.overDueCount);

                    elem.find('[act=color_type]').beTip({dir: 'left'});
                    elem.find('[act=finish_work]').beTip({dir: 'left'});
                    elem.find('[act=createSchedule_today]').beTip({dir: 'left'});

                    //$('.qtip-content').hide();
                    //新建任务或日程
                    var isIndustry = SESSION.tenantType;
                    if(isIndustry == 1){//判断是否是行业版
                        var button = elem.find("[act=createSchedule_today]");
                        var navMenu = elem.find("[act='schedule_create_menu']");
                        button.rkEasyMenu({
                            menu: navMenu,
                            onSelect: function (li) {
                                var act = li.attr('act');
                                if(act == "create_schedule"){
                                    var ownerUser = {};
                                    ownerUser.id = SESSION.user.id;
                                    ownerUser.name = SESSION.user.name;
                                    var opt = {
                                        ownerUser: ownerUser,
                                        //otherUser: ownerUser,
                                        isAllDay: false,
                                        act: 'create'
                                    };
                                    var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil');
                                    scheduleUtil.popupEditor(opt);
                                }else if(act == "create_visit_plan"){
                                    require.async(["oa/js/schedule/visit/visitPlanCreateDialogCtrl"],function(){
                                        rk.dialog({
                                            title: rk.i18n('PAGE_NEW_VISIT'),
                                            success: function (contentElem) {
                                                contentElem.visitPlanCreateDialogCtrl();//初始化弹框内容的Ctrl
                                            },
                                            footer: ['cancel', {
                                                act: 'ok', visible: true, text: rk.i18n('CRM_CORE_SAVE')
                                            }]
                                        });
                                    });
                                }
                            }
                        });

                    }else {
                        elem.on('click', 'a[act=createSchedule_today]', function () {
                            var ownerUser = {};
                            ownerUser.id = SESSION.user.id;
                            ownerUser.name = SESSION.user.name;
                            var opt = {
                                ownerUser: ownerUser,
                                //otherUser: ownerUser,
                                isAllDay: false,
                                act: 'create'
                            };
                            var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil');
                            scheduleUtil.popupEditor(opt);
                        });
                    }
                }
            }).fail(function(def, code, message) {
                def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
            });
        },
        _initPage: function(data){
            var me = this;
            var elem = me.element;

            if(data.schedules.length == 0 && data.tasks.length == 0){
                elem.find("ul[act=portal-task-list]").eq(0).hide();
                elem.find("div[act=portal-task-footer]").eq(0).hide();
            } else {
                elem.find("div[act=portal-task-blank]").eq(0).hide();
            }
        },
        _bindHandler: function(){
            var me = this;
            var elem = me.element;

            //点击更多
            elem.on('click', 'a[act=more]', function() {
                //隐藏任务tip
                elem.find("div[act=task_tip]").hide();
                for(var i=me.data.defaultNumber; i<=me.data.total; i++){
                    elem.find("li[act=task_" + i + "]").eq(0).show();
                }
                //隐藏更多
                elem.find("a[act=more]").eq(0).hide();
            });


            //点击XX条过期任务
            elem.on('click', 'a[act=taskdue]', function() {
                //隐藏任务tip
                elem.find("div[act=task_tip]").hide();
                //缺省将过期任务展开
                rk.oa.showApp('task', null, {taskType:"overdue"});
            });

            //绑定任务的鼠标滑过事件
            elem.on('mouseover', 'li[tipact=task_tip_href]',function() {
                var taskId = $(this).attr("taskId");
                var objectName = $(this).attr("objectName");

                window.clearTimeout(me['openTimer'+taskId]);
                //清除上一个li的隐藏事件
                window.clearTimeout(me[me['prehideTimer']]);

                me['openTimer'+taskId] = window.setTimeout(function() {
                    //展示任务tip
                    if (objectName == "task") {
                        if(me["task"+taskId] != undefined){
                            me._rendTaskDetail(me["task"+taskId]);

                            elem.find("div[act=task_tip]").show();
                            elem.find("div[id=task-" + taskId + "]").show();

                            me._calTipTopLeft(taskId);
                        } else {
                            var url = '/json/crm_task/detail.action';
                            rk.post(url, {
                                taskId: taskId
                            }).done(function (json) {
                                if (json.status == 0) {
                                    json.data.task.description = json.data.task.description.replace(/\n/g, '<br>');
                                    //me.data = json.data;
                                    me._formatTaskDetailData(json.data);
                                    //me["task"+taskId] = json.data;
                                    me._rendTaskDetail(json.data);

                                    elem.find("div[act=task_tip]").show();
                                    elem.find("div[id=task-" + taskId + "]").show();

                                    me._calTipTopLeft(taskId);
                                } else if (json.status == 300002) {
                                    //var html = rk.templateText(require("oa/tmpl/approval/tpl_approval_content_default_detail.tpl"), {
                                    //    noticeError: '抱歉，该任务已删除！'
                                    //});
                                    elem.find("div[act=task_tip]").show();
                                    //elem.find("div[act=task_tip]").html("");
                                    //elem.find("div[act=task_tip]").html(html);
                                    elem.find("div[act=task_tip]").html('<div class="helpful_box"><div class="helpful_content">'+rk.i18n('TASK_IS_DELETED')+'</div></div>');
                                    me._calTipTopLeft(taskId);
                                } else {
                                    //var html = rk.templateText(require('oa/tmpl/approval/tpl_approval_content_default_detail.tpl'), {
                                    //    noticeError: rk.i18n('LOAD_ERROR')
                                    //});
                                    elem.find("div[act=task_tip]").show();
                                    //elem.find("div[act=task_tip]").html("");
                                    //elem.find("div[act=task_tip]").html(html);
                                    elem.find("div[act=task_tip]").html('<div class="helpful_box"><div class="helpful_content">' + rk.i18n('LOAD_ERROR') + '</div></div>');
                                    me._calTipTopLeft(taskId);
                                }
                            });
                        }
                    } else {
                        //展示日程tip
                        if(me["schedule"+taskId] != undefined){
                            me._rendScheduleDetail(me["schedule"+taskId]);
                            //me.addHandlers(json.data);

                            elem.find("div[act=task_tip]").show();
                            elem.find("div[id=task-" + taskId + "]").show();
                            me._calTipTopLeft(taskId);
                        } else {
                            $.getJSON('/json/crm_schedule/detail.action?scheduleId=' + taskId, function (json) {
                                if (json.status == '0') {
                                    if (json.data.schedule.accessible) {
                                        me["schedule"+taskId] = json.data;
                                        me._rendScheduleDetail(json.data);
                                        //me.addHandlers(json.data);

                                        elem.find("div[act=task_tip]").show();
                                        elem.find("div[id=task-" + taskId + "]").show();
                                        me._calTipTopLeft(taskId);
                                    } else {
                                        elem.find("div[act=task_tip]").show();
                                        elem.find("div[act=task_tip]").html("");
                                        elem.find("div[act=task_tip]").html('<div class="helpful_box"><div class="helpful_content">'+rk.i18n('SCHEDULE_18')+'</div></div>');
                                        me._calTipTopLeft(taskId);
                                    }
                                } else if (json.status == '300002') {
                                    elem.find("div[act=task_tip]").show();
                                    elem.find("div[act=task_tip]").html("");
                                    elem.find("div[act=task_tip]").html('<div class="helpful_box"><div class="helpful_content">'+rk.i18n('SCHEDULE_19')+'</div></div>');
                                    me._calTipTopLeft(taskId);
                                } else if (json.status == '300001') {
                                    elem.find("div[act=task_tip]").show();
                                    elem.find("div[act=task_tip]").html("");
                                    elem.find("div[act=task_tip]").html('<div class="helpful_box"><div class="helpful_content">'+rk.i18n('SCHEDULE_18')+'</div></div>');
                                    me._calTipTopLeft(taskId);
                                } else {
                                    $.msg(rk.i18n('SCHEDULE_20')+ json.statusText);
                                }
                            });
                        }
                    }
                }, 500);

            });

            //绑定任务的鼠标离开事件
            elem.on('mouseleave', 'li[tipact=task_tip_href]',function() {
                var taskId = $(this).attr("taskId");
                var objectName = $(this).attr("objectName");

                window.clearTimeout(me['openTimer'+taskId]);

                //记录上一个li的隐藏事件id
                me['prehideTimer'] = 'hideTimer'+taskId;

                me['hideTimer'+taskId] = window.setTimeout(function(){
                    //隐藏任务tip
                    elem.find("div[act=task_tip]").hide();
                }, 1500);

            });

            //完成任务
            elem.on('click', 'a[act=finish_work]', function() {
                //完成任务，并且刷新页面
                $.post('/json/crm_task/change-status.action', {
                    taskId: $(this).attr("taskId"),
                    taskStatus: 2
                }, null, 'json').done(function(json) {
                    if (json.status == 0) {
                        $.msg(rk.i18n('TASK_HAVE_FINISHED'), 1);

                        var $taskPanel = $('#index_task_panel');

                        //重新加载今天工作
                        $taskPanel.todayWorkCtrl();

                        $('.qtip-content').hide();
                        $('.qtip-dark-rk').hide();
                    } else {
                        $.msg(rk.i18n('TASK_CHANGE_STATUS_ERROR'));
                    }
                }).fail(function(def, code, message) {
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                });
            });
        },
        _calTipTopLeft:function(taskId){
            var me = this;
            var elem = this.element;
            var li = elem.find('li[taskId=' + taskId +']');
            var left = $(li).position().left - 400;
            var top = $(li).position('top').top + 20;

            elem.find("div[act=show_tip]").eq(0).css({left:left+'px', top: top+'px'});
            elem.on('mouseover', 'div[act=show_tip]', function() {
                window.clearTimeout(me['hideTimer'+taskId]);
            });

            elem.on('mouseleave', 'div[act=show_tip]', function() {
                //隐藏任务tip
                elem.find("div[act=task_tip]").hide();
            });
            //elem.find("div[act=field_content_today_work]").beScroll();

        },
        _rendScheduleDetail: function(data) {
            var me = this,
                elem = this.element;
            var schedule = data.schedule;
            if(data.schedule.colorType.dummyType == 32){//巡访计划
                me._formatVisitPlanData(data);
                return;
            }

            schedule.creater = data.users[schedule.createdBy].name;
            schedule.createdDate = Globalize.format(new Date(schedule.createdAt - 0), 'yyyy-MM-dd');
            schedule.createdTime = Globalize.format(new Date(schedule.createdAt - 0), 'HH:mm');

            schedule.duration = $.map((function() {
                var sd = Globalize.format(new Date(schedule.startDate - 0), 'yyyy-MM-dd'),
                    st = Globalize.format(new Date(schedule.startDate - 0), 'HH:mm');
                var ed = Globalize.format(new Date(schedule.endDate - 0), 'yyyy-MM-dd');
                var et = Globalize.format(new Date(schedule.endDate - 0), 'HH:mm');
                if (schedule.isAllDay == '1') {
                    if (sd == ed) {
                        return [sd];
                    } else {
                        return [sd, rk.i18n('TO'), ed];
                    }
                } else {
                    if (sd == ed) {
                        if (st == et) {
                            return [sd, st];
                        } else {
                            return [sd, st, rk.i18n('TO'), et];
                        }
                    } else {
                        return [sd, st, rk.i18n('TO'), ed, et];
                    }
                }
            })(), function(s) {
                return '<span>' + s + '</span>';
            }).join('');

            schedule.rptinfo = (function(o) {
                if (o.isRecur == '1') {
                    return '<div class="schedule_field relation_field"><div class="field_name"></div><div class="field_content"><div class="tixin">' +
                        $.map([
                            ['', rk.i18n('SCHEDULE_25'), rk.i18n('SCHEDULE_26'), rk.i18n('SCHEDULE_27')][o.frequency], rk.i18n('SCHEDULE_REPEAT'), ',',
                            o.recurStopCondition == '1' ? rk.i18n('SCHEDULE_NO_END') : (rk.i18n('SCHEDULE_54') + $.datepicker.formatDate('yy-mm-dd', new Date(+o.recurStopValue)) + rk.i18n('SCHEDULE_55'))
                        ], function(str) {
                            return str ? '<span>' + str + '</span>' : null;
                        }).join('') + '</div></div></div>';
                } else {
                    return '';
                }
            })(schedule);

            schedule.remind = {
                '-1': rk.i18n('SCHEDULE_NO_REMIND'),
                '0': rk.i18n('SCHEDULE_IN_TIME'),
                '600': rk.i18n('SCHEDULE_EARLY_10MINUTE'),
                '1800': rk.i18n('SCHEDULE_EARLY_30MINUTE'),
                '3600': rk.i18n('SCHEDULE_EARLY_1HOUR'),
                '7200': rk.i18n('SCHEDULE_EARLY_2HOUR'),
                '21600': rk.i18n('SCHEDULE_EARLY_6HOUR'),
                '86400': rk.i18n('SCHEDULE_EARLY_1DAY'),
                '54000': rk.i18n('SCHEDULE_9_INDAY'),
                '-32400': rk.i18n('SCHEDULE_9_BEFOREDAY')
            }[schedule.reminder];

            schedule.acceptMember = $.map(data.acceptMember || [], function(uid) {
                return '<li><a href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '" target="_blank"><img ucard="uid=' + uid + '" src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (schedule.acceptMember) {
                schedule.members = '<ul class="task_people_list">' + schedule.acceptMember + '</ul>';
            }
            schedule.waitingMember = $.map(data.waitingMember || [], function(uid) {
                return '<li><a href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '" target="_blank"><img ucard="uid=' + uid + '" src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (schedule.waitingMember) {
                schedule.waiting = '<div class="confirmed_people participants"><span class="tip">'+rk.i18n('SCHEDULE_28')+'</span><ul class="task_people_list">' + schedule.waitingMember + '</ul></div>';
            }
            schedule.rejectMember = $.map(data.rejectMember || [], function(uid) {
                return '<li><a href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '" target="_blank"><img ucard="uid=' + uid + '" src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (schedule.rejectMember) {
                schedule.reject = '<div class="confirmed_people participants"><span class="tip">'+rk.i18n('SCHEDULE_29')+'</span><ul class="task_people_list">' + schedule.rejectMember + '</ul></div>';
            }
            if (schedule.description) {
                //schedule.description = '<div id="task_description_label" class="task_description schedule_task_description"><span class="task_list_noneinfo">' + schedule.description + '</span></div>';
                schedule.description = schedule.description.replace(/\n/g, '<br>');
            } else {
                schedule.description = rk.i18n('NO_DESCRIPTION');
            }

            if (schedule.objectId) {
                schedule.relation = (function(o) {
                    var entry = data.sourceEntity,
                        rMap = {
                            1: {
                                name: SESSION.keywords.account,
                                url: '/final/account.action?id=',
                                cname: 'account'
                            },
                            3: {
                                name: SESSION.keywords.opportunity,
                                url: '/final/opportunity.action?id=',
                                cname: 'opportunity'
                            },
                            2: {
                                name: SESSION.keywords.contract,
                                url: '/final/contact.action?id=',
                                cname: 'contact'
                            },
                            6: {
                                name: SESSION.keywords.campaign,
                                url: '/final/campaign.action?id=',
                                cname: 'campaign'
                            },
                            11: {
                                name: SESSION.keywords.lead,
                                url: '/final/lead.action?id=',
                                cname: 'leads'
                            },
                            66:{
                                name: SESSION.keywords.agent,
                                url: '/final/agent.action?id=',
                                cname: 'terminal'
                            },
                            67:{
                                name: SESSION.keywords.terminal,
                                url: '/final/terminal.action?id=',
                                cname: 'terminal'
                            }
                        };
                    return ['<div class="schedule_field relation_field"><div class="field_name">'+rk.i18n('SCHEDULE_RELATE_BUSINESS')+'</div><div class="field_content"><div class="show_ralation_bussiness"><span class="task_group"><p class="feed-group-name"><span class="feed-group-class ', rMap[o.belongId].cname, '"></span><a title="'+rk.i18n('SCHEDULE_24') + '：', rMap[o.belongId].name, '" href="', rMap[o.belongId].url + entry.id, '">', entry.name, '</a></p></span></div></div></div>'].join('');
                })(schedule);
            }
            schedule.files = data.files.length;

            var $detail = rk.templateText(require('../../../tmpl/index/todaywork/tpl_schedule_tip.tpl'), {
                task: schedule
            });
            elem.find("div[act=task_tip]").html("");
            elem.find("div[act=task_tip]").html($detail);
        },
        _formatVisitPlanData:function(data){
           var $this = this,
                $elem = this.element,
                opt = this.options;
            data.isPrivate = data.schedule.isPrivate == '1' ? '<span class="lock"></span>' : '';
            data.id = data.schedule.id;
            //data.name = data.schedule.name;
            data.name = "拜访:" + data.schedule.from.name;
            if(data.users[data.schedule.createdBy]) {
                var createUser = data.users[data.schedule.createdBy];
                data.createTimeOrUser = "该拜访计划于 " + moment(data.schedule.createdAt - 0).format("YYYY-MM-DD HH:mm") + "" + " 由 <a target='_blank' href='/final/user.action?uid="+createUser.id+"'>" + createUser.name +"</a> 创建";
            }


            data.between = (function(o) {
                //+' 到' + $.datepicker.formatDate('yy-mm-dd', new Date(+o.recurStopValue)) + '结束'
                if(o.isRecur == '1') {
                    return $.map([$.datepicker.formatDate('yy-mm-dd', new Date(+o.startDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.startDate)), rk.i18n('TO'), $.datepicker.formatDate('yy-mm-dd', new Date(+o.recurStopValue)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.recurStopValue))], function (str) {
                        return str ? '<span>' + str + '</span>' : null;
                    }).join('');
                }else{
                    return $.map([$.datepicker.formatDate('yy-mm-dd', new Date(+o.startDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.startDate)), rk.i18n('TO'), $.datepicker.formatDate('yy-mm-dd', new Date(+o.endDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.recurStopValue))], function (str) {
                        return str ? '<span>' + str + '</span>' : null;
                    }).join('');
                }
            })(data.schedule);

            data.rptinfo = (function(o) {
                if (o.isRecur == '1') {
                    var recurString = $.map([
                        ['', rk.i18n('SCHEDULE_25'), rk.i18n('SCHEDULE_26'), rk.i18n('SCHEDULE_27')][o.frequency], rk.i18n('SCHEDULE_REPEAT'), ',',
                        o.recurStopCondition == '1' ? rk.i18n('SCHEDULE_NO_END') : ('')
                    ], function(str) {
                        return str ? '<span>' + str + '</span>' : null;
                    }).join('');
                    if(data.schedule.rules){
                        var rules = data.schedule.rules
                        if(o.frequency == 2){
                            var week_days = rules.split(',');
                            var week_days_json={
                                "1":"周一",
                                "2":"周二",
                                "3":"周三",
                                "4":"周四",
                                "5":"周五",
                                "6":"周六",
                                "7":"周日"
                            };
                            var endString = '';
                            for(var i=0;i<week_days.length;i++){
                                endString += week_days_json[week_days[i]];
                                if(i != week_days.length -1){
                                    endString += ',';
                                }
                            }
                            recurString = "计划将于每" + endString +"重复";
                            data.frequencyName = "按周重复";
                        }else if(o.frequency == 3){
                            data.frequencyName = "按月重复";
                        }

                    }
                    return '<div class="schedule_field relation_field"><div class="field_name"></div><div class="field_content"><div class="tixin">' +
                        recurString + '</div></div></div>';
                } else {
                    return '';
                }
            })(data.schedule);

            data.acceptMember = $.map(data.acceptMember, function(uid) {
                return '<li><a target="_blank" href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '"><img src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (data.acceptMember) {
                data.members = '<ul class="task_people_list">' + data.acceptMember + '</ul>';
            }
            data.task={id:data.schedule.id};
            var html = require('../../../tmpl/index/todaywork/tpl_visit_plan_tip.tpl'); //template('template_calScheduleViewer', data);
            html = rk.templateText(html, data);
            $elem.find("div[act=task_tip]").html("");
            $elem.find("div[act=task_tip]").html(html);
        },
        _formatTaskDetailData: function(data) {
            var me = this,
                elem = this.element,
                opt = this.options;
            var t =data.task;
            var isAdmin = SESSION.user.id == t.createdBy,
                isOwner = SESSION.user.id == t.ownerId,
                isJoiner = $.inArray(SESSION.user.id,data.members) > -1;
            var rMap = {
                1: {
                    name: SESSION.keywords.account,
                    url: '/final/account.action?id=',
                    cname: 'account'
                },
                2: {
                    name: SESSION.keywords.contact,
                    url: '/final/contact.action?id=',
                    cname: 'contact'
                },
                3: {
                    name: SESSION.keywords.opportunity,
                    url: '/final/opportunity.action?id=',
                    cname: 'opportunity'
                },
                6: {
                    name: SESSION.keywords.campaign,
                    url: '/final/campaign.action?id=',
                    cname: 'campaign'
                },
                11: {
                    name: SESSION.keywords.lead,
                    url: '/final/lead.action?id=',
                    cname: 'lead'
                }
            };

            $.extend(t, {
                ownerName:data.users[t.ownerId].name,
                ownerIcon:data.users[t.ownerId].icon || DEFAULTS.USER_DEFAULT_ICON,
                description: t.description.replace(/\n/g, '<br>') || rk.i18n('NO_DESCRIPTION'),
                relObject: t.belongId ? rk.templateText(
                    '<span class="task_group"><p class="feed-group-name"><span title="{{belongName}}" class="feed-group-class {{belongClass}}"></span><a title="{{objectName}}" href="{{objectpage}}" target="_blank" class="">{{objectName}}</a></p></span>', {
                        belongName: rMap[t.belongId].name,
                        belongClass: rMap[t.belongId].cname,
                        objectpage: rMap[t.belongId].url + t.objectId,
                        objectName:data.sourceEntity.name
                    }) : '<span class="task_list_noneinfo">'+rk.i18n('TASK_HAVE_NO_SET')+'</span>',
                objectLink: (!t.belongId && (isAdmin || isOwner)) ? '<a class="edit_link js-belong" title="" href="javascript:;">'+rk.i18n('TASK_ADD_REL_BUSINESS')+'</a>' : '',
                statusName: t.status == 1 && t.expired == "true" ? rk.i18n('TASK_IS_OVERDUE') :data.taskStatus[t.status].name,
                statusClass: t.status == 1 && t.expired == "true" ? 'overdue' : 'normal',
                finishClass: t.status == 2 ? 'done' : 'normal',
                reminderName: {
                    '-1': rk.i18n('SCHEDULE_NO_REMIND'),
                    '0': rk.i18n('SCHEDULE_IN_TIME'),
                    '300': rk.i18n('SCHEDULE_EARLY_5MINUTE'),
                    '600': rk.i18n('SCHEDULE_EARLY_10MINUTE'),
                    '1800': rk.i18n('SCHEDULE_EARLY_30MINUTE'),
                    '3600': rk.i18n('SCHEDULE_EARLY_1HOUR'),
                    '7200': rk.i18n('SCHEDULE_EARLY_2HOUR'),
                    '21600': rk.i18n('SCHEDULE_EARLY_6HOUR'),
                    '86400': rk.i18n('SCHEDULE_EARLY_1DAY'),
                    '172800': rk.i18n('SCHEDULE_EARLY_2DAY')
                }[t.reminder],
                members:data.members.length ? ['<ul class="people_list task_people_list" joiner>', $.map(data.members, function(id) {
                    var o =data.users[id];
                    o.icon = o.icon || DEFAULTS.USER_DEFAULT_ICON;
                    return rk.templateText('<li joinerid="{{id}}" title="{{name}}" icon="{{icon}}"><a href="javascript:;"><img src="{{icon}}"></a></li>', o);
                }).join(''), '</ul>'].join('') : '<span class="task_list_noneinfo js-joiner-span">'+rk.i18n('TASK_HAVE_NO_SET')+'</span>',

                typeName: t.ownerId == t.createdBy ? rk.i18n('TASK_CREATE') : rk.i18n('TASK_ASSIGN'),

                createdByName:data.users[t.createdBy].name,
                createdByIcon:data.users[t.createdBy].icon || DEFAULTS.USER_DEFAULT_ICON,

                updatedByName:data.users[t.updatedBy].name,
                updatedByIcon:data.users[t.updatedBy].icon || DEFAULTS.USER_DEFAULT_ICON,

                planFinishDateFmt: moment(t.planFinishDate - 0).format('YYYY-MM-DD HH:mm'),
                actualFinishDateFmt: moment(t.actualFinishDate - 0).format('YYYY-MM-DD HH:mm'),
                createdAtFmt: moment(t.createdAt - 0).format('YYYY-MM-DD HH:mm'),
                updatedAtFmt: moment(t.updatedAt - 0).format('YYYY-MM-DD HH:mm'),
                commentCount:data.commentCount,
                fileCount:data.files.length,

                taskReAssign: (isAdmin && t.status == 4) ? '' : 'hidden',
                taskOperateHidden: (isOwner && t.status == 3) ? '' : 'hidden',
                powerDelete: isAdmin ? '' : 'hidden',
                powerExit: isJoiner ? '' : 'hidden',
                powerEditDisabled: isAdmin || isOwner ? '' : 'disabled',
                powerCheckboxDisabled: isAdmin || isOwner ? '' : '_disabled',
                powerAssignerHidden: (isOwner && t.status == 3) ? 'hidden' : '',
                powerEditHidden: isAdmin || isOwner ? '' : 'hidden',
                powerReminder: isAdmin || isOwner || isJoiner ? '' : 'hidden'
            });

            me["task"+data.task.id] = data;
        },
        _rendTaskDetail: function(data) {
            var me = this,
                elem = this.element
            var task =data.task;
            var isAdmin = SESSION.user.id == task.createdBy,
                isOwner = SESSION.user.id == task.ownerId,
                isJoiner = $.inArray(SESSION.user.id,data.members) > -1;
            var $detail = rk.templateText(require('../../../tmpl/index/todaywork/tpl_task_tip.tpl'), {
                task: task
            });
            elem.find("div[act=task_tip]").html("");
            elem.find("div[act=task_tip]").html($detail);


            if (task.status == 4 && isAdmin) { //我分配的被人拒绝的全字段编辑
                var $statusCheck = elem.find('a.js-status');
                $statusCheck.addClass('_disabled');
                $statusCheck.parent().attr('class', 'task_tickbox_disabled');
                elem.find('div.task_status').remove();
                elem.find('div.task_tool').remove();
                elem.find('a.edit_link').remove();
                elem.find('div.task_save').show();
                me._addEventHandler();
            } else { //其它情况抠框编辑
                if (isJoiner) {
                    elem.find('a.js-belong').remove();
                }
                if (task.status == 3) { //未接受状态不可以编辑
                    elem.find('a.edit_link').remove();
                    elem.find('div.js_edit_div').addClass('disabled');
                    var $statusCheck = elem.find('a.js-status');
                    $statusCheck.addClass('_disabled');
                    $statusCheck.parent().attr('class', 'task_tickbox_disabled');
                    if (!isAdmin) {
                        elem.find('a.js-delete').remove();
                        elem.find('a.js-exit').remove();
                    }
                }
            }
            elem.find('a.hidden').remove();
        },
    _formatData: function(data) {
        var me = this;
        var elem = me.element;
        var todayList = new Array();
        //debugger
        var dataSchedules = [];
        var visitPlans = [];
        var otherSchedules = [];
        $.each(data.schedules, function (i, schedule) {
            if(schedule.colorType.dummyType == 32){
                visitPlans.push(schedule);
            }else{
                otherSchedules.push(schedule);
            }
        });
        dataSchedules = dataSchedules.concat(visitPlans,otherSchedules);
        $.each(dataSchedules, function (i, schedule) {
            //schedule.startDate = Globalize.format(new Date(schedule.startDate - 0), 'HH:mm');
            //schedule.endDate = Globalize.format(new Date(schedule.endDate - 0), 'HH:mm');

            todayList[i] = {};
            todayList[i] = schedule;
            todayList[i].objectName = "schedule";
            todayList[i].href = "/final/schedule.action?scheduleId=" + schedule.id;
            //todayList[i].scheduleId
            todayList[i].startDate = Globalize.format(new Date(schedule.startDate - 0), 'HH:mm');
            todayList[i].endDate = Globalize.format(new Date(schedule.endDate - 0), 'HH:mm');

            todayList[i].portaltaskdiv = "portal-schedule-div";
            todayList[i].tasktickbox = "schedule-tickbox";
            todayList[i].img = '<span class="' + schedule.colorType.color + '" title="' + schedule.colorType.name + '" act="color_type"></span>';
            todayList[i].tasktext = "schedule-text";
            if(todayList[i].startDate == "00:00" && todayList[i].endDate == "00:00"){
                if(!todayList[i].colorType || todayList[i].colorType.dummyType != 32) {
                    todayList[i].time = rk.i18n('SCHEDULE_ALLDAY');
                }
            } else {
                todayList[i].time = todayList[i].startDate + "-" + todayList[i].endDate;
            }
            if(schedule.colorType.dummyType == 32){//巡访计划
                todayList[i].name = "拜访："+schedule.from.name;
                todayList[i].href = "/final/visitplan.action?planId=" + schedule.id;
                todayList[i].finishStatus = schedule.visitsFinishStatus;
            }else{
                todayList[i].name = schedule.name;
            }
            //todayList[i].fromName = schedule.from.name;
        });

        $.each(data.tasks, function (i, task) {
            //task.planFinishDate = Globalize.format(new Date(task.planFinishDate - 0), 'HH:mm');

            task.ownerIcon = data.users[task.ownerId].icon || DEFAULTS.USER_DEFAULT_ICON;

            if (task.reminder == "-1" || task.reminder == "")
                task.reminderName = rk.i18n('SCHEDULE_NO_REMIND');
            else if (task.reminder == "0")
                task.reminderName = rk.i18n('SCHEDULE_IN_TIME');
            else if (task.reminder == "300")
                task.reminderName = rk.i18n('SCHEDULE_EARLY_5MINUTE');
            else if (task.reminder == "600")
                task.reminderName = rk.i18n('SCHEDULE_EARLY_10MINUTE');
            else if (task.reminder == "1800")
                task.reminderName = rk.i18n('SCHEDULE_EARLY_30MINUTE');
            else if (task.reminder == "3600")
                task.reminderName = rk.i18n('SCHEDULE_EARLY_1HOUR');
            else if (task.reminder == "7200")
                task.reminderName = rk.i18n('SCHEDULE_EARLY_2HOUR');
            else if (task.reminder == "21600")
                task.reminderName = rk.i18n('SCHEDULE_EARLY_6HOUR');
            else if (task.reminder == "86400")
                task.reminderName = rk.i18n('SCHEDULE_EARLY_1DAY');
            else if (task.reminder == "172800")
                task.reminderName = rk.i18n('SCHEDULE_EARLY_2DAY');

            todayList[i + me.data.schedules.length] = {};
            todayList[i + me.data.schedules.length] = task;
            todayList[i + me.data.schedules.length].objectName = "task";
            todayList[i + me.data.schedules.length].href = "/final/task.action?taskId=" + task.id;
            //todayList[i].taskId
            todayList[i + me.data.schedules.length].startDate = Globalize.format(new Date(task.planFinishDate - 0), 'HH:mm');
            //todayList[i + me.data.schedules.length].endDate = "";

            todayList[i + me.data.schedules.length].portaltaskdiv = "portal-task-div";
            todayList[i + me.data.schedules.length].tasktickbox = "task_tickbox";
            if(SESSION.user.id == task.ownerId) {
                todayList[i + me.data.schedules.length].tasktickbox = "task_tickbox";
                todayList[i + me.data.schedules.length].img = '<a href="javascript:void(0);" class="normal" title="'+rk.i18n('TASK_CLICK_FINISHED')+'" taskId="' + task.id + '" act="finish_work"></a>';
            } else {
                todayList[i + me.data.schedules.length].tasktickbox = "task_tickbox_disabled";
                todayList[i + me.data.schedules.length].img = '<a href="javascript:void(0);" class="normal" title="'+rk.i18n('SCHEDULE_31')+'" act="color_type"></a>';
                //todayList[i + me.data.schedules.length].img = '<a href="javascript:void(0);" class="nc_title normal" oldtitle="您不是任务负责人，不能操作" title="" data-hasqtip="true" aria-describedby="qtip-131"></a>';
            }
            todayList[i + me.data.schedules.length].tasktext = "task_text";
            todayList[i + me.data.schedules.length].time = Globalize.format(new Date(task.planFinishDate - 0), 'HH:mm');
            todayList[i + me.data.schedules.length].name = task.taskName;
            //todayList[i + me.data.schedules.length].fromName = task.from.name;
        });

        todayList = _(todayList).sortBy(function (item) {
            return item.startDate;
        }).value();
        me.data.todayList = todayList;
    }
    });
});